package foo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

public class WorkerRunnable implements Runnable {

	private final Socket		clientSocket;
	private final String		serverText;
	private final AtomicBoolean	keepReplying	= new AtomicBoolean(true);

	public WorkerRunnable(Socket aSocket, String aTitle) {
		this.clientSocket = aSocket;
		this.serverText = aTitle;
	}

	public void run() {
		try {
			processClientRequest(clientSocket);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public void stop() {
		keepReplying.getAndSet(false);
	}

	private void processClientRequest(Socket clientSocket) throws IOException, InterruptedException {
		InputStream input = clientSocket.getInputStream();
		OutputStream output = clientSocket.getOutputStream();

		long time = System.currentTimeMillis();

		while (keepReplying.get()) {
			output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " + this.serverText + " - " + time + "").getBytes());
			Thread.sleep(5 * 1000);
		}

		output.close();
		input.close();
		System.out.println("Request processed:" + time);
	}
}
